package com.example.cloud.service.customer.impl;

import com.alibaba.fastjson.JSONArray;
import com.example.cloud.dao.customer.ComplaintRecordRepository;
import com.example.cloud.dao.mongdb.system.MongoUserRepository;
import com.example.cloud.model.customer.ComplaintRecord;
import com.example.cloud.model.system.User;
import com.example.cloud.service.customer.ComplaintRecordService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class ComplaintRecordServiceImpl implements ComplaintRecordService {

    private static final Logger logger = Logger.getLogger(ComplaintRecordServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private ComplaintRecordRepository complaintRecordRepository;

    @Autowired
    private MongoUserRepository mongoUserRepository;

    @Override
    public List<ComplaintRecord> findAll() {
        return complaintRecordRepository.findByAccountIdAndDeleteFlag(RequestUtil.getLoginUser().getAccountId(),0);
    }

    @Override
    public ComplaintRecord findOne(Long id) {
        return complaintRecordRepository.findOne(id);
    }

    @Override
    @Transactional
    public ComplaintRecord doSave(ComplaintRecord record) {
        if(record.getId() == null){
            User user = RequestUtil.getLoginUser();
            record.setAccountId(user.getAccountId());
            record.setOrganId(user.getOrganId());
            record.setOrganName(user.getOrganName());
            if(StringUtils.isNotBlank(record.getRelatedPersonnel())){
                String rpn = "";
                JSONArray ja = JSONArray.parseArray(record.getRelatedPersonnel());
                for (Object o : ja) {
                    User u = mongoUserRepository.findOne(Long.valueOf(o.toString()));
                    if(u != null){
                        rpn += "," + u.getUsername();
                    }
                }
                rpn = rpn.replaceFirst(",","");
                record.setRelatedPersonnelName(rpn);
            }
        }
        BusinessUtil.appendRecord(record);
        return complaintRecordRepository.save(record);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        complaintRecordRepository.deleteByIdIn(ids);
    }
}
